package com.devframe.component.ftlprocess.freemarker.directive;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;

import com.devframe.component.ftlprocess.FTLProcessGlobalConstants;
import com.devframe.component.ftlprocess.meta.Report;


import freemarker.core.Environment;
import freemarker.ext.beans.BeanModel;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateHashModel;
import freemarker.template.TemplateModel;
/**
 * 
 *<pre><b><font color="blue">ReportDirective</font></b></pre>
 *
 *<pre><b>&nbsp;--描述说明--</b></pre>
 * <pre> <@report></@report> 指令的解析器  </pre>
 * <pre>
 * <b>--样例--</b>
 *   ReportDirective obj = new ReportDirective();
 *   obj.method();
 * </pre>
 * JDK版本：JDK1.4
 * @author  <b>詹保山</b>
 */
public class ReportDirective implements TemplateDirectiveModel {

	public void execute(Environment env, Map params, TemplateModel[] models,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		Object val = env.getConfiguration().getSharedVariable(
				FTLProcessGlobalConstants.RESOLVE_SHARED_NAME);
		// 如果是解析 <@report></@report>的指令，需要解析出其对应的属性
		if (FTLProcessGlobalConstants.RESOLVE_REPORT_MARK.equals(val.toString())) {
			if (env.getDataModel() instanceof TemplateHashModel) {
				TemplateHashModel thm = (TemplateHashModel) env.getDataModel();
				// 获取报表的的属性
				Object obj = thm.get(FTLProcessGlobalConstants.ReportTag);
				if (obj != null && (obj instanceof BeanModel)) {
					BeanModel beanModel = (BeanModel) obj;
					Report report = (Report) beanModel.getWrappedObject();
					// 参数过滤器
					Object var = params.get(FTLProcessGlobalConstants.ReportAttr_ParamFilter);
					if (var != null && StringUtils.isNotEmpty(var.toString())) {
						report.setParamFilter(var.toString());
					}
					// 结果集过滤器
					var = params.get(FTLProcessGlobalConstants.ReportAttr_ResultFilter);
					if (var != null && StringUtils.isNotEmpty(var.toString())) {
						report.setResultFilter(var.toString());
					}
					// 导出EXCEL文件模板
					var = params.get(FTLProcessGlobalConstants.ReportAttr_XlsFile);
					if (var != null && StringUtils.isNotEmpty(var.toString())) {
						report.setXlsFile(var.toString());
					}
//					// 导出文件的名称
//					var = params.get(GlobalConstants.ReportAttr_ExportFileName);
//					if (var != null && StringUtils.isNotEmpty(var.toString())) {
//						report.setExportFileName(var.toString());
//					}
				}
			}
		}
		body.render(env.getOut());
	}
}
